import mongoose from 'mongoose';
import log4js from 'koa-log4';
import tags from './tags';

const logger = log4js.getLogger('UrgentTeacherReplacement');

process.on('unhandledRejection', (reason) => {
  logger.error(reason);
});

class UrgentTeacherReplacementRobot {
  async getSystemRobot() {
    if (this.systemRobot) return this.systemRobot;

    const User = mongoose.model('User');
    const systemRobot = User.getSystemRobot();
    this.systemRobot = systemRobot;
    return systemRobot;
  }

  async getTeacherChannel(teacherId) {
    const User = mongoose.model('User');
    const user = await User.findOne({ jiuquId: `Teacher:${teacherId}` });

    return user ? user.channels[0] : null;
  }

  /**
   * @param {*} messageHandler
   * @param {*} event {
   *   fromTeacherId,
   *   toTeacherId,
   *   reason
   *   roomId,
   *   beginAt,
   *   endAt,
   *   lessonId
   * }
   */
  async sendMessage(messageHandler, event) {
    const systemRobot = await this.getSystemRobot();
    const [fromTeacherChannelId, toTeacherChannelId] = await Promise.all([
      this.getTeacherChannel(event.fromTeacherId),
      this.getTeacherChannel(event.toTeacherId),
    ]);

    logger.info('from %s channelId %s, to %s channelId %s', event.fromTeacherId, fromTeacherChannelId, event.toTeacherId, toTeacherChannelId);

    [fromTeacherChannelId, toTeacherChannelId].forEach((channelId) => {
      messageHandler.post(channelId, systemRobot, {
        body: JSON.stringify(event),
        subType: 'URGENT_TEACHER_REPLACEMENT',
      });
    });
  }

  async handle({ tag, event, messageHandler }) {
    if (tag !== tags.URGENT_REPLACEMENT) return;
    logger.info('Receive Teacher Replacement Event %s -> %s', event.fromTeacherId, event.toTeacherId);
    this.sendMessage(messageHandler, event);
  }
}

export default new UrgentTeacherReplacementRobot();
